/**
 *
 */
package com.longrise.android.byjk.plugins.login;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.PhoneUtils;
import com.longrise.android.byjk.widget.view.InputBoxView;
import com.longrise.common.glide.RoundCornersTransformation;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 找回密码
 *
 * @author callxkj 2015-12-28
 * @see
 * @since 1.0
 */
public class ForgetPasswordActivity extends BaseActivity implements OnClickListener, TextWatcher, View.OnFocusChangeListener {

    private static final String TAG = "ForgetPasswordActivity";

    private Button mBt_confirm;

    private InputBoxView mBvname;

    private EditText mEtphn;
    private String mSignphone = "";

    private InputBoxView mBvvfcode;

    private TextView mTvgetvf;

    private ImageView mIvVfcode; //验证码

    private EditText mEtvfcode;
    private InputBoxView mBvpassword;
    private InputBoxView mBvpassword_cf;
    private boolean mFlage = false;
    private Handler mHandler = new Handler();

    private ImageView mVfCode;
    private ImageView mForgetPwd;


    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {

            mTvgetvf.setText("重新获取(" + millisUntilFinished / 1000 + "s)");

        }

        @Override
        public void onFinish() {
            getVftoNorm();
        }
    };
    private Toolbar mToolbar;


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_forgetpassword;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle(AppUtil.getString(R.string.forgetpsword));
        setSupportActionBar(mToolbar);

        mBt_confirm = (Button) findViewById(R.id.forgetpassword_confirm);
        mBt_confirm.setEnabled(false);
        mTvgetvf = (TextView) findViewById(R.id.forgetpasword_pic2);
        mBvname = (InputBoxView) findViewById(R.id.forgetpasword_username);
        mEtphn = (EditText) findViewById(R.id.forgetpasword_text);
        mBvvfcode = (InputBoxView) findViewById(R.id.forgetpasword_vfcode);

        mIvVfcode = (ImageView) findViewById(R.id.vfcode_pic2);
        mEtvfcode = (EditText) findViewById(R.id.vfcode_text); //验证码输入框
        mBvpassword = (InputBoxView) findViewById(R.id.forgetpassword_newpw);//新密码
        mBvpassword_cf = (InputBoxView) findViewById(R.id.forgetpassword_cfpw); //确认密码
        mVfCode = (ImageView) findViewById(R.id.vfcode_pic1);
        mForgetPwd = (ImageView) findViewById(R.id.forgetpasword_pic1);

        regEvent();
        initData();

        EditText bvnameText = mBvname.getEditText();
        bvnameText.setInputType(InputType.TYPE_CLASS_TEXT);
        bvnameText.setText(CacheUtils.getString(Control.USERNAME, null));
        bvnameText.setSelection(bvnameText.getText().length());

    }

    public void initData() {
        mBvpassword.setRightClickMode(InputBoxView.PASSWORD);
        mBvpassword.setTextMode(InputBoxView.PASSWORD);
        mBvpassword_cf.setRightClickMode(InputBoxView.PASSWORD);
        mBvpassword_cf.setTextMode(InputBoxView.PASSWORD);
        mIvVfcode.setScaleType(ImageView.ScaleType.FIT_XY);
        loadVfcode();
        getPhoneNumber();
    }

    /**
     * 加载验证码
     */
    private void loadVfcode() {
        new Thread() {
            public void run() {
                try {
                    // 获取连接
                    HttpURLConnection conn = (HttpURLConnection) new URL(UrlConstants.VFCODE_URL).openConnection();
                    conn.setConnectTimeout(30 * 1000);// 设置连接服务器超时时间
                    conn.setReadTimeout(30 * 1000);// 设置读取响应超时时间
                    // 连接网络
                    conn.connect();
                    // 获取响应码
                    int code = conn.getResponseCode();
                    if (200 == code) {
                        String cookie = conn.getHeaderField("Set-Cookie");
                        LoadDataManager.getInstance().setCookie(UrlConstants.VFCODE_URL, cookie);
                        InputStream is = conn.getInputStream();
                        final Bitmap bitmap = BitmapFactory.decodeStream(is);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
//                                mIvVfcode.setImageBitmap(bitmap);
                                RoundCornersTransformation transformation =
                                        new RoundCornersTransformation(mContext,
                                                AppUtil.dip2px(4),
                                                RoundCornersTransformation.CornerType.RIGHT);
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                                byte[] bytes = baos.toByteArray();
                                Glide.with(ForgetPasswordActivity.this)
                                        .load(bytes)
                                        .bitmapTransform(transformation)
                                        .into(mIvVfcode);
                            }
                        });
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            ;
        }.start();
    }

    public void regEvent() {
        mIvVfcode.setOnClickListener(this);
        mBt_confirm.setOnClickListener(this);
        mTvgetvf.setOnClickListener(this);
        mBvname.setRightClickMode(InputBoxView.USERIF);

        //判断是否有输入框没有填写
        mBvname.getEditText().addTextChangedListener(this);//身份证或者账号
        mEtvfcode.addTextChangedListener(this);//图片验证码
        mEtphn.addTextChangedListener(this);//手机号码
        mBvvfcode.getEditText().addTextChangedListener(this);//手机验证码
        mBvvfcode.setRightClickMode(InputBoxView.USERIF);
        mBvpassword.getEditText().addTextChangedListener(this);//新密码
        mBvpassword_cf.getEditText().addTextChangedListener(this);//确认密码

        mBvname.getEditText().setOnFocusChangeListener(this);
        mEtphn.setFocusable(false);
        mToolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mEtvfcode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String icoCheck = mEtvfcode.getText().toString().trim();
                if (!TextUtils.isEmpty(icoCheck) && !"".equals(icoCheck)) {
                    mVfCode.setSelected(true);
                } else {
                    mVfCode.setSelected(false);
                }

            }
        });

        mEtphn.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String phone = mEtphn.getText().toString().trim();
                if (!TextUtils.isEmpty(phone) && !"".equals(phone)) {
                    mForgetPwd.setSelected(true);
                } else {
                    mForgetPwd.setSelected(false);
                }

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.forgetpassword_confirm: // 确定
                toConfirm();
                break;
            case R.id.forgetpasword_pic2: // 获取验证码
                String usersfzhh = mBvname.getText();
                toGetvfcode(usersfzhh, mSignphone);  //sjz
                break;

            case R.id.vfcode_pic2: //点击验证码 重新加载
                loadVfcode();
                break;
            default:
                break;
        }
    }

    /**
     * 确认提交
     */
    private void toConfirm() {
        final String usersfzh = mBvname.getText(); //身份证或者账号
        String tpvfcode = mEtvfcode.getText().toString().trim(); //图片验证码
//        String signphone = mEtphn.getText().toString().trim(); //手机号码
        if (!PhoneUtils.isPhoneNumber(mSignphone)) { // 判断是否是电话号码
            DZZWTools.showToast(ForgetPasswordActivity.this, getString(R.string.txzqsjh), 0);
            return;
        }
        String code = mBvvfcode.getText(); //手机验证码
        String password = mBvpassword.getText();  //新密码
//        if (!password.matches("[0-9a-z-A-Z_]{6,18}")) {
//            DZZWTools.showToast(ForgetPasswordActivity.this, getString(R.string.pw_content), 0);
//            return;
//        }
        String password2 = mBvpassword_cf.getText(); //确认密码
//        if (!password.equals(password2)) {
//            DZZWTools.showToast(ForgetPasswordActivity.this, getString(R.string.pw_not_same), 0);
//            return;
//        }
        EntityBean bean = new EntityBean();
        bean.set("username", usersfzh);
        bean.set("newpwd", password);
        bean.set("confirmpwd", password2);
        bean.set("imgcode", tpvfcode);
        bean.set("mobile", mSignphone);
        bean.set("mobilecode", code);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        mBt_confirm.setClickable(false);
        DZZWTools.showWaitDialog(this);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_uResetPWD", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    String resultdesc = (String) bean.get("resultdesc");
                    int resultstate = (Integer) bean.get("resultstate");
                    if (resultstate == 1) {

                        CacheUtils.setString(Control.USERNAME, usersfzh);
                        finish();
                    } else {
                    }
                    DZZWTools.showToast(ForgetPasswordActivity.this, resultdesc, 0);
                } catch (Exception e) {
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(ForgetPasswordActivity.this, getResources().getString(R.string.networkerror), 0);
            }

            @Override
            public void onFinished(String key, String service) {
                mBt_confirm.setClickable(true);
                DZZWTools.dismissDialog(null);
            }
        });
    }

    /**
     * 获取验证码
     */
    private void toGetvfcode(final String usersfzh, final String signphone) {

        if (TextUtils.isEmpty(usersfzh)) {
            DZZWTools.showToast(ForgetPasswordActivity.this, getString(R.string.sfzzh_null), 0);
            return;
        }

        if (TextUtils.isEmpty(signphone)) {
            DZZWTools.showToast(ForgetPasswordActivity.this, getString(R.string.sjh_null), 0);
            return;
        }
        if (!PhoneUtils.isPhoneNumber(signphone)) {
            DZZWTools.showToast(ForgetPasswordActivity.this, getString(R.string.txsjh), 0);
            return;
        }
        EntityBean bean = new EntityBean();
        bean.set("usersfzh", usersfzh);
        bean.set("signphone", signphone);
        bean.set("isregphone", "1");
        bean.set("imgcode", mEtvfcode.getText().toString().trim());
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);

        mTvgetvf.setClickable(false);
        mTvgetvf.setTextColor(Color.parseColor("#666666"));
        DZZWTools.showWaitDialog(ForgetPasswordActivity.this);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_sGetVarCode", fbean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    int resultstate = (Integer) bean.get("resultstate");
                    String resultdesc = (String) bean.get("resultdesc");
                    if (resultstate == 1) {
                        timer.start();
                    } else {
                        getVftoNorm(); //可能账号与手机号码不匹配 用户需重新输入后倒计时
                    }
                    DZZWTools.showToast(ForgetPasswordActivity.this, resultdesc, 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null);

            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                getVftoNorm();
                DZZWTools.showToast(ForgetPasswordActivity.this, getResources().getString(R.string.networkerror), 0);
            }
        });
    }

    /**
     * 获取手机号码
     */
    private void getPhoneNumber() {
        String usersfzhh = mBvname.getText();
        if (TextUtils.isEmpty(usersfzhh)) {
            return;
        }
        EntityBean bean = new EntityBean();
        bean.set("username", usersfzhh);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_login_sUserInfoByNameOrCardno", fbean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    int resultstate = (Integer) bean.get("resultstate");
                    String resultdesc = (String) bean.get("resultdesc");
                    if (resultstate == 1) {
                        EntityBean resultBean = bean.getBean("result");
                        mSignphone = resultBean.getString("signphone");
                        mEtphn.setText(hidePhoneNumber(mSignphone));
                    } else {
                        mEtphn.setText("");
                        DZZWTools.showToast(ForgetPasswordActivity.this, resultdesc, 0);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished(String key, String service) {

            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(ForgetPasswordActivity.this, getResources().getString(R.string.networkerror), 0);
            }
        });

    }

    /**
     * sjz加入  return 155****5055
     */
    private String hidePhoneNumber(String phone) {
        try {//按照11位计算
            if (PhoneUtils.isPhoneNumber(phone) && phone.length() == 11) {
                StringBuilder phoneBuilder = new StringBuilder();
                phoneBuilder.append(phone.substring(0, 3)).append("****").append(phone.substring(7, 11));
                return phoneBuilder.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return phone;
    }


    /**
     * 让获取验证码的按钮恢复正常状态
     */
    private void getVftoNorm() {
        mTvgetvf.setClickable(true);
        mTvgetvf.setText("获取验证码");
        mTvgetvf.setTextColor(Color.parseColor("#0791FF"));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        UserInfor.getInstance().setVfcode("");
        timer.cancel();
        timer = null;
    }


    //-------以下三个为输入框字数的更改--------
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        boolean b = checkText();
        if (b) {
            mBt_confirm.setEnabled(true);
        } else {
            mBt_confirm.setEnabled(false);
        }
    }
    //-------以上三个为输入框字数的更改--------

    /**
     * 检查是否全部text有填写
     *
     * @return 全部填写返回true
     */
    private boolean checkText() {
        String usersfzh = mBvname.getText(); //身份证或者账号
        if (TextUtils.isEmpty(usersfzh)) {
            //sjz 加入，"" && null时清空电话
            mEtphn.post(new Runnable() {
                @Override
                public void run() {
                    mEtphn.setText("");
                }
            });
            return false;
        }

        String tpvfcode = mEtvfcode.getText().toString().trim(); //图片验证码
        if (TextUtils.isEmpty(tpvfcode)) {
            return false;
        }

//        String signphone = mEtphn.getText().toString().trim(); //手机号码
        if (TextUtils.isEmpty(mSignphone)) {  //sjz
            return false;
        }

        String code = mBvvfcode.getText(); //手机验证码
        if (TextUtils.isEmpty(code)) {
            return false;
        }

        String password = mBvpassword.getText();  //新密码
        if (TextUtils.isEmpty(password)) {
            return false;
        }

        String password2 = mBvpassword_cf.getText(); //确认密码
        if (TextUtils.isEmpty(password2)) {
            return false;
        }
        return true;
    }

    //用户名或身份证号码输入完成的监听
    @Override
    public void onFocusChange(View view, boolean b) {
        mBvname.setRightIcVisible(b);
        if (!b) {
            getPhoneNumber();
        }
    }
}
